<template>
  <v-data-table
    :headers="headers"
    :items="desserts"
    :search="search"
    :footer-props="footer"
    class="elevation-1"
  >
    <template v-slot:top>
      <v-toolbar flat color="white">
        <v-toolbar-title>{{ title }}</v-toolbar-title>
        <v-divider class="mx-4" inset vertical></v-divider>

        <v-dialog v-model="dialog" max-width="500px">
          <template v-slot:activator="{ on, attrs }">
            <!-- <v-icon color="primary" v-bind="attrs" v-on="on">mdi-database-plus</v-icon> -->
            <v-btn icon large color="primary" v-bind="attrs" v-on="on"
              ><v-icon>mdi-database-plus</v-icon></v-btn
            >
          </template>
          <v-card>
            <v-card-title>
              <span class="headline">{{ formTitle }}</span>
            </v-card-title>

            <v-card-text>
              <v-container>
                <v-row>
                  <!-- 仿写下面的col -->
                  <v-col cols="12" sm="6" md="6">
                    <v-text-field
                      v-model="editedItem.name"
                      label="用户名"
                    ></v-text-field>
                  </v-col>
                  <v-col cols="12" sm="6" md="6">
                    <v-text-field
                      v-model="editedItem.nick"
                      label="昵称"
                    ></v-text-field>
                  </v-col>
                  <v-col cols="12" sm="6" md="6">
                    <v-select
                      v-model="editedItem.roleId"
                      :items="options"
                      label="角色"
                    ></v-select>
                  </v-col>
                  <v-col cols="12" sm="6" md="6">
                    <v-text-field
                      v-model="editedItem.desc"
                      label="简介"
                    ></v-text-field>
                  </v-col>
                </v-row>
              </v-container>
            </v-card-text>
            <v-card-actions>
              <v-spacer></v-spacer>
              <v-btn color="error" text @click="close">Cancel</v-btn>
              <v-btn color="success" text @click="save">Save</v-btn>
            </v-card-actions>
          </v-card>
        </v-dialog>
        <v-spacer></v-spacer>
        <v-text-field
          v-model="search"
          append-icon="mdi-magnify"
          label="Search"
          single-line
          hide-details
        ></v-text-field>
      </v-toolbar>
    </template>
    <template v-slot:item.roleId="{ item }">
      <v-chip color="secondary">{{ item.role.name }}</v-chip>
    </template>
    <template v-slot:item.actions="{ item }">
      <v-icon color="primary" class="mr-2" @click="editItem(item)">
        mdi-pencil
      </v-icon>
      <v-icon color="warning" @click="deleteItem(item)"> mdi-delete </v-icon>
    </template>
    <template v-slot:no-data>
      <v-btn color="primary" @click="refresh">Reset</v-btn>
    </template>
  </v-data-table>
</template>

<script>
// 引用各自的API
import {
  GetListUser,
  CreateOneUser,
  UpdateOneUser,
  RemoveOneUser,
} from "@/api/user.js";
import { GetListRole } from "@/api/role.js";
import { mapGetters } from "vuex";

export default {
  data: () => ({
    dialog: false,
    search: "",
    desserts: [],
    editedIndex: -1,
    options: [],
    // Todo 修改下面三个字段
    // ============================================================================
    title: "用户",
    headers: [
      {
        text: "用户名",
        align: "start",
        sortable: false,
        value: "name",
      },
      {
        text: "昵称",
        align: "start",
        sortable: false,
        value: "nick",
      },
      {
        text: "角色",
        align: "start",
        sortable: false,
        value: "roleId",
      },
      {
        text: "简介",
        align: "start",
        sortable: false,
        value: "desc",
      },

      { text: "Actions", value: "actions", sortable: false },
    ],
    editedItem: { name: "", nick: "", desc: "", roleId: "" },
    defaultItem: {
      name: "",
      nick: "",
      desc: "",
      roleId: "",
    },
    // ============================================================================
  }),
  computed: {
    ...mapGetters("app", ["footer"]),
    formTitle() {
      return this.editedIndex === -1
        ? "新建" + this.title
        : "更新" + this.title;
    },
  },

  watch: {
    dialog(val) {
      val || this.close();
    },
  },

  created() {
    this.initialize();
    this.refresh();
  },

  methods: {
    refresh() {
      // Todo 这里从后台请求数据，写入this.desserts
      GetListUser().then((res) => {
        this.desserts = res.body;
      });
    },
    initialize() {
      // Todo 如果Dialog中设计Select,请在此处初始化this.options
      GetListRole().then((res) => {
        const options = res.body;
        this.options = options.map((o) => {
          return {
            text: o.name,
            value: o.id,
          };
        });
      });
    },
    editItem(item) {
      this.editedIndex = this.desserts.indexOf(item);
      this.editedItem = Object.assign({}, item);
      this.dialog = true;
    },
    close() {
      this.dialog = false;
      this.$nextTick(() => {
        this.editedItem = Object.assign({}, this.defaultItem);
        this.editedIndex = -1;
      });
    },

    //  下面两个方法需要增加相应的后台交互操作
    save() {
      if (this.editedIndex > -1) {
        //   update
        // Object.assign(this.desserts[this.editedIndex], this.editedItem);
        UpdateOneUser(this.editedItem).then(res=>{
          this.$msg.info(res.msg)
          this.refresh()
        })
      } else {
        //   create
        // this.desserts.push(this.editedItem);
        CreateOneUser(this.editedItem).then(res=>{
          this.$msg.info(res.msg)
          this.refresh()
        })
      }
      this.close();
    },
    deleteItem(item) {
      // const index = this.desserts.indexOf(item);
      confirm("确认删除?") &&
        // this.desserts.splice(index, 1);
        RemoveOneUser(item.id).then(res=>{
          this.$msg.info(res.msg)
          this.refresh()
        })
    },
  },
};
</script>